import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Response } from 'express';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {

    console.log(exception,'exception');
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    
    let statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
    let responseBody: any = {
      code: HttpStatus.INTERNAL_SERVER_ERROR,
      success: false,
      message: exception['message'][0] || '服务器内部错误',
      data: null,
    };

    if (exception instanceof HttpException) {
      const exceptionResponse = exception.getResponse();
      statusCode = exception.getStatus();
      
      if (typeof exceptionResponse === 'object') {
        responseBody = {
          ...exceptionResponse,
          success: false,
        };
      }
    }

    response.status(statusCode).json(responseBody);
  }
}